package bot.controller;

import bot.conf.PathConf;
import bot.mapper.ArcImageMapper;
import bot.mapper.BotImageMapper;
import bot.pojo.ArcImage;
import bot.pojo.ArcImageExample;
import bot.pojo.BotImage;
import bot.pojo.BotImageExample;
import com.alibaba.fastjson.JSONObject;
import net.sf.json.JSONArray;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.io.*;
import java.nio.file.Files;
import java.util.*;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("image/")
public class ImageController {//获取图片
    //创建一个对象
    Random df = new Random();
    @Autowired
    private RedisTemplate<String,String> redisTemplate;
    private BotImageExample botImageExample = new BotImageExample();

    @Autowired
    private BotImageMapper botImageMapper;
    @GetMapping("/getImage/{id}")
    public Object getImage(@PathVariable("id") Integer id){
        botImageExample.clear();
        BotImageExample.Criteria criteria = botImageExample.createCriteria();
        criteria.andStatusEqualTo(id.toString());
        List<BotImage> botImages = botImageMapper.selectByExample(botImageExample);
        int i = df.nextInt(botImages.size());
        if(botImages.size() != 0){
            //创建json集合
            JSONArray jsonArray = JSONArray.fromObject(botImages);//有效时间一小时
            if(id == 1){
                redisTemplate.opsForValue().set("imageList",jsonArray.toString(),600 * 10, TimeUnit.SECONDS);
            }else if(id == 2){
                redisTemplate.opsForValue().set("HimageList",jsonArray.toString(),600 * 10, TimeUnit.SECONDS);
            }
           //A EventChannel<Event> eventEventChannel = GlobalEventChannel.INSTANCE.parentScope(this);
            return botImages.get(i);
        }
    return null;
    }
    @GetMapping("/newImage")
    public String sendNewImage(String imageName){
        botImageExample.clear();
        BotImage botImage = new BotImage();
        botImage.setImagename(imageName);
        botImage.setStatus("1");
        int insert = botImageMapper.insert(botImage);
        if(insert == 1){
            //清空缓存
            redisTemplate.opsForValue().set("imageList","");
            return "true";
        }
        return "false";
    }
        //把某个文件夹下的所有图片存入
    @GetMapping("/sendImage")
    public String sendImage(String path) throws IOException {//把本体图片存入数据库
        File file = new File("E:\\BaiduNetdiskDownload\\R18\\img");
        List<String> st = new ArrayList<>();
        List<String> ergodic = ergodic(file, st);
        BotImage botImage = new BotImage();
        for (int i = 0 ; i< ergodic.size() ; i ++){
            Object o = copyFile(ergodic.get(i), "/home/bot/UserImageBotImage/");
            botImageExample.clear();
            botImage.setImagename(o.toString());
            botImage.setStatus("2");
            botImageMapper.insert(botImage);
            System.out.println(o.toString());
        }
        return null;
    }

    /**
     * 拷贝文件
     * @param file1  要拷贝的文件路径
     * @param file2  要复制到的文件夹目录
     * @return
     */
    public static Object copyFile(String file1, String file2) {
        UUID uuid = UUID.randomUUID();
        String str = uuid.toString();
        String uuidStr = str.replace("-", "");

        File in = new File(file1);
        File out = new File(file2);
        //要拷贝的文件
        if (!in.exists()) {
            System.out.println(in.getAbsolutePath() + "要拷贝的文件路径错误！！！");
            return false;
        }
        //目标文件夹
        if (!out.exists()) {
            out.mkdirs();
        }
        FileInputStream fis = null;
        FileOutputStream fos = null;
        File file = new File(file2 + "\\" + uuidStr + ".jpg");
        try {
            //创建读取 要拷贝的文件
            fis = new FileInputStream(in);
            //创建 要复制到的文件

            fos = new FileOutputStream(file);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        int c;
        //创建字节数组
        byte[] b = new byte[1024 * 5];
        try {
            //写入文件
            while ((c = fis.read(b)) != -1) {
                fos.write(b, 0, c);
            }
            fis.close();
            fos.flush();
            fos.close();
            return file.getName();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }

    private static List<String> ergodic(File file,List<String> resultFileName){
        File[] files = file.listFiles();
        if(files==null)return resultFileName;// 判断目录下是不是空的
        for (File f : files) {
            if(f.isDirectory()){// 判断是否文件夹
                //resultFileName.add(f.getPath());
                ergodic(f,resultFileName);//递归， 调用自身,查找子目录
            }else
                resultFileName.add(f.getPath());
        }
        return resultFileName;
    }
    ArcImageExample arcImageExample = new ArcImageExample();
    @Autowired
    private ArcImageMapper arcImageMapper;
    @PostMapping("/arcImage")
    public String ArcIamge(@RequestBody String arcImage){//把本体图片存入数据库
       ArcImage arcImage1 = JSONObject.parseObject(arcImage,ArcImage.class);

        arcImageExample.clear();
        ArcImageExample.Criteria criteria = arcImageExample.createCriteria();
        //查询的哪个名字的哪个难度的歌
        criteria.andSendnameEqualTo(arcImage1.getSendname());
        criteria.andLevelEqualTo(arcImage1.getLevel());
        criteria.andMusicnameEqualTo(arcImage1.getMusicname());

        List<ArcImage> arcImages = arcImageMapper.selectByExample(arcImageExample);
        if (arcImages.size() == 0){//不存在才走新增
            int insert = arcImageMapper.insert(arcImage1);
            if (insert == 1){
                return "true";
            }
        }else{
            //存在走更新，而且删除之前保存的
            File file = new File("/home/bot/UserImageArcImage/" + arcImages.get(0).getGameimage());
            file.delete();
            arcImageExample.clear();
            //把指定id数据改了
            criteria.andIdEqualTo(arcImages.get(0).getId());
            int i = arcImageMapper.updateByExampleSelective(arcImage1, arcImageExample);
            if (i == 1){
                return "true";
            }

        }
        return "false";
    }
    @Autowired
    PathConf PathConf;
    //bot删除数据库图片
    @GetMapping("/delImage")
    public String delImage(String id){
        id = id.trim();
        botImageExample.clear();
        botImageExample.createCriteria().andIdEqualTo(Integer.valueOf(id));

        List<BotImage> botImages = botImageMapper.selectByExample(botImageExample);
        try {
            File file = new File(PathConf.normalimgPath + botImages.get(0).getImagename());
            boolean delete = file.delete();
            System.out.println(delete);
        }catch (Exception e){
            return null;
        }

        int i = botImageMapper.deleteByExample(botImageExample);
        if(i == 1){
            return "true";
        }else {
            return null;
        }
    }


    //清除色图
    @GetMapping("/delAllImageR18")
    public void delAllImageR18(){
        botImageExample.clear();
        botImageExample.createCriteria().andStatusEqualTo("2");
        List<BotImage> botImages = botImageMapper.selectByExample(botImageExample);
        for (int i = 0; i < botImages.size() ; i ++){
            File file = new File(PathConf.HimgPath + botImages.get(i).getImagename());
            System.out.println(botImages.get(i).getImagename());
            file.delete();
            botImageExample.clear();
            botImageExample.createCriteria().andIdEqualTo(botImages.get(i).getId());
            botImageMapper.deleteByExample(botImageExample);
        }
    }
}
